package com.jxb.six;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 电话号码的字母组合
 *
 * 输入：digits = "23"
 * 输出：["ad","ae","af","bd","be","bf","cd","ce","cf"]
 *
 * @author jiaobo
 * @date Created in 2025/1/4 13:58
 **/
public class LetterCombinations_17 {

    public static void main(String[] args) {
        String strs = "23";
        letterCombinations(strs);
    }

    public static List<String> letterCombinations(String digits) {
        List<String> combinations = new ArrayList<String>();
        if (digits.length() == 0) {
            return combinations;
        }

        //数字和字母的映射表
        Map<Character, String> phoneMap = new HashMap<Character, String>() {{
            put('2', "abc");
            put('3', "def");
            put('4', "ghi");
            put('5', "jkl");
            put('6', "mno");
            put('7', "pqrs");
            put('8', "tuv");
            put('9', "wxyz");
        }};

        backtrack(combinations,phoneMap,digits,0,new StringBuffer());
        return combinations;
    }

    private static void backtrack(List<String> combinations, Map<Character, String> phoneMap, String src, int index,
                           StringBuffer combination) {
        if (index == src.length()) {
            combinations.add(combination.toString());
        }else {
            char digit = src.charAt(index);
            String letters = phoneMap.get(digit);
            int lettersCount = letters.length();
            //进行遍历
            for (int i = 0;i < lettersCount; i++) {
                combination.append(letters.charAt(i));
                //继续递归处理当前节点下的子节点
                backtrack(combinations,phoneMap,src,index+1,combination);
                //当前节点处理完成，往上回庶
                combination.deleteCharAt(index);
            }
        }
    }

}
